<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyid">
              <j-search-select-tag v-model="model.companyid" placeholder="请选择公司"
                dict="sys_depart where org_type='1',depart_name,id"></j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billcode">
              <a-input v-model="model.billcode" placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billdate">
              <j-date v-model="model.billdate" placeholder="请输入单据日期"></j-date>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="采购部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purdeptid">
              <j-select-depart v-model="model.podeptid" placeholder="请输入采购部门" :pid="model.companyid"></j-select-depart>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="采购人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="puremptid">
              <c-select-user :buttons="false" :multi="false" v-model="model.poemptid" placeholder="请输入采购人员">
              </c-select-user>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="采购组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purteamid">
              <a-input v-model="model.purteamid" placeholder="请输入采购组"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remarks">
              <a-input v-model="model.remarks" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="询价截止日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="validdate">
              <j-date v-model="model.validdate" placeholder="请输入询价截止日期"></j-date>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="询价供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="vendorlinkid">
              <c-select-vendor v-model="model.vendorlinkid" :mult="true" :buttons="false" placehodler="请选择供应商"
                required></c-select-vendor>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="询价单分录" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table keep-source :ref="refKeys[0]" :loading="scminquiryitemTable.loading"
          :columns="scminquiryitemTable.columns" :dataSource="scminquiryitemTable.dataSource" :maxHeight="300"
          :disabled="formDisabled" :rowNumber="true" :rowSelection="true" :alwaysEdit="true"
          @valueChange="handleValueChange" :toolbar="true">
          <template slot="toolbarSuffix" :disabled="formDisabled">
            <!-- <a-button type="primary" @click="getPrData" :disabled="formDisabled">参照采购计划</a-button> -->
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <po-refer-pr ref="PoReferPr" @ok="getSelectPr"></po-refer-pr>
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import JFormContainer from '@/components/jeecg/JFormContainer'
import PoReferPr from '../../../base/custom/PoReferPr.vue'
import { toFixedNumber } from 'xe-utils/methods'
import { queryMaterialById, queryMaterialVoInfoById } from '@/api/erp/commonapi'

export default {
  name: 'ScminquiryForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    PoReferPr
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {},
      refKeys: ['scminquiryitem'],
      tableKeys: ['scminquiryitem'],
      activeKey: 'scminquiryitem',
      // 询价单分录
      scminquiryitemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: 'parentid',
            key: 'parentid',
            type: JVXETypes.hidden,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '物料',
            key: 'materialid',
            type: JVXETypes.materialSelect,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '物料编号',
            key: 'materialcode',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '物料名称',
            key: 'materialname',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '计量单位',
            key: 'uomid',
            type: JVXETypes.sel_search,
            width: '100px',
            dictCode: 'scmuom,uomname,id',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '询价数量',
            key: 'qty',
            type: JVXETypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '询价价格',
            key: 'price',
            type: JVXETypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '需求日期',
            key: 'requestdate',
            type: JVXETypes.date,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '要求到货日期',
            key: 'requiredate',
            type: JVXETypes.date,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '报价进度',
            key: 'quoteFlag',
            type: JVXETypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            customRender: function (text) {
              if (text) {
                if (text === '0' || text === '') {
                  return '未报价'
                } else if (text === '1') {
                  return '部分报价'
                } else if (text === '2') {
                  return '全部报价'
                }
              } else {
                return '未报价'
              }
            }
          },
          {
            title: '报价次数',
            key: 'quoteNum',
            type: JVXETypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            disabled: true,
            customRender: text => {
              return '2222'
            }
          }
        ]
      },
      url: {
        add: '/rfq/scminquiry/add',
        edit: '/rfq/scminquiry/edit',
        queryById: '/rfq/scminquiry/queryById',
        scminquiryitem: {
          list: '/rfq/scminquiry/queryScminquiryitemByMainId'
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled: {
      get () {
        return this.disabled
      },
      set (v) {
        this.disabled = v
      }
    }
  },
  created () { },
  methods: {
    getPrData () {
      this.$nextTick(() => {
        //console.log(this.$refs.LinkBillList);
        this.$refs.PoReferPr.show('其它', '采购计划', '', '1,3', this.model.vendorid, this.model.companyid)
      })
    },
    getSelectPr (selectedRowKeys) {
      let ids = ''
      for (let i = 0; i < selectedRowKeys.length; i++) {
        if (selectedRowKeys[i] != undefined) {
          ids += selectedRowKeys[i] + ','
        }
      }
      let url = '/pr/scmpr/queryScmpritemListByIds'
      let param = { ids: ids }
      getAction(url, param).then(async res => {
        if (res) {
          let resu = res.result.records || res.result
          //console.log("resu" + resu);
          //todo 给新增行赋值
          let info = []
          if (resu != null && resu.length > 0) {
            for (let i = 0; i < resu.length; i++) {
              let currentValue = parseFloat(resu[i]['qty'], 2) * parseFloat(resu[i]['taxinprice'], 2)
              currentValue = toFixedNumber(currentValue, 2)
              let materials = await queryMaterialVoInfoById({ materialid: resu[i]['materialid'] })
              let taxrate = 0
              if (
                materials.result == null ||
                materials.result.taxrate === '' ||
                materials.result.taxrate === null ||
                materials.result.taxrate === undefined
              ) {
                taxrate = 0
              } else {
                taxrate = materials.result.taxrate
              }
              const newData = {
                materialid: resu[i]['materialid'],
                materialcode: resu[i]['materialcode'],
                materialname: resu[i]['materialname'],
                qty: resu[i]['qty'],
                price: resu[i]['taxinprice'],
                uomid: resu[i]['uomid'],
                // taxrate: taxrate,
                // taxexprice: toFixedNumber(parseFloat(resu[i]["taxinprice"], 2) * (100 - taxrate) / 100, 2),
                // taxexvalue: toFixedNumber(parseFloat(resu[i]["taxinprice"], 2) * (100 - taxrate) / 100 * resu[i]['qty'], 2),
                fromid: resu[i]['parentid'],
                fromitemid: resu[i]['id'],
                taxinvalue: currentValue,
                requestdate: resu[i].prdate
                // deliverydate: resu[i]["prorder_date"]
              }
              info.push(newData)
            }
            this.scminquiryitemTable.dataSource = info
          }
        }
      })
    },
    addBefore () {
      this.scminquiryitemTable.dataSource = []
    },
    getAllTable () {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter () {
      this.$nextTick(() => { })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.scminquiryitem.list, params, this.scminquiryitemTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm (allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch(e => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData (allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        scminquiryitemList: allValues.tablesValue[0].tableData
      }
    },
    validateError (msg) {
      this.$message.error(msg)
    }
  }
}
</script>

<style scoped></style>
